package cglib;

import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.CallbackHelper;
import net.sf.cglib.proxy.Enhancer;

/**
 * @ClassName CglibProxyTest
 * @Description
 * @Author lichuanqi
 * @Date 2022/5/2 15:46
 * @Version 1.0
 **/
public class CglibProxyTest {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        //test1();
        test2();
    }

    private static void test1() {
        Enhancer enhancer = new Enhancer();
        enhancer.setClassLoader(TargetClass.class.getClassLoader());
        enhancer.setSuperclass(TargetClass.class);
        enhancer.setCallback(new MyMethodInterceptor());
        TargetClass target = (TargetClass) enhancer.create();
        target.sayHello();
    }

    /**
     * @Author lichuanqi
     * @Description 通过setCallbackFilter选择Callback
     * @Date 19:50 2022/5/9
     * @Param []
     * @return void
     **/
    private static void test2() throws InstantiationException, IllegalAccessException {
        Enhancer enhancer = new Enhancer();
        enhancer.setClassLoader(TargetClass.class.getClassLoader());
        enhancer.setSuperclass(TargetClass.class);
        //enhancer.setCallback(new MyMethodInterceptor());
        enhancer.setCallbacks(new Callback[] {new MyMethodInterceptor(), new MyMethodInterceptor1()});
        //enhancer.setStrategy();
        enhancer.setCallbackFilter(new MyCallbackFilter());

//        Class aClass = enhancer.createClass();
//        TargetClass target = (TargetClass) aClass.newInstance();
//        target.sayHello();
        TargetClass target = (TargetClass) enhancer.create();
        target.sayHello();

        target.sayHello1();
    }
}
